package com.solidumgame.martillo.nail
{
	
	
	import com.greensock.TweenMax;
	import com.greensock.easing.Linear;
	import com.pblabs.box2D.CollisionEvent;
	import com.pblabs.engine.PBE;
	import com.pblabs.engine.entity.IEntity;
	import com.solidumgame.martillo.nail.events.NailGenericEvent;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.geom.Point;
	
	public class Nail extends EventDispatcher
	{
		
		public static const SIZE_LARGE:int = 0;
		public static const SIZE_MEDIUM:int = 1;
		public static const SIZE_SMALL:int = 2;
		
		public static const TYPE:String = "Nail";
		
		private static var numNail:int = 0;
		
		protected var myEntity:IEntity;
		protected var spatialComp:NailSpatialComponent;
		protected var render:NailRendererComponent;
		protected var nailLogic:NailLogicComponent;
		protected var nailHitSound:NailSoundComponent;
		
		protected var nailSize:int;
		
		protected var _isNailed:Boolean = false;
		
		public function Nail(position:Point, size:int)
		{
			super();
			
			nailSize = size;
			
			spatialComp  = new NailSpatialComponent(position, size);
			
			render = new NailRendererComponent(size);
			
			nailLogic = new NailLogicComponent(size);
			
			nailHitSound = new NailSoundComponent();
			
			// Allocate new entity and add components.
			myEntity = PBE.allocateEntity();
			
			myEntity.addComponent(spatialComp, "Spatial");
			myEntity.addComponent(nailLogic, "Logic");
			myEntity.addComponent(render, "Renderer");
			myEntity.addComponent(nailHitSound,"NailHitSound");
			
			myEntity.initialize("Nail"+numNail++);		
			
			//Add listeners of components
			myEntity.eventDispatcher.addEventListener(NailGenericEvent.NAIL_NOT_NAILED_EVENT,onNailNotNailed);
			myEntity.eventDispatcher.addEventListener(NailGenericEvent.NAIL_NAILED_EVENT,onNailNailed);		
		}	
		
		//On nail nailed throw event		
		protected function onNailNailed(e:NailGenericEvent):void{
			
			myEntity.eventDispatcher.removeEventListener(NailGenericEvent.NAIL_NAILED_EVENT,onNailNailed);
			this._isNailed = true;
			dispatchEvent(new NailGenericEvent(e.type));
		}
		
		//On nail nailed throw event		
		protected function onNailNotNailed(e:NailGenericEvent):void{
			
			myEntity.eventDispatcher.removeEventListener(NailGenericEvent.NAIL_NOT_NAILED_EVENT,onNailNotNailed);
			this._isNailed = true;
			dispatchEvent(new NailGenericEvent(e.type));
		}
		
		public function get isNailed():Boolean
		{
			return _isNailed;
		}
		
		public function remove():void{
			if(myEntity)
				myEntity.destroy();
			myEntity = null;
			spatialComp = null;
			render = null;
			nailLogic = null;
			nailHitSound = null;
		}		
		
	}
}